import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:oktoast/oktoast.dart';
import 'package:rapid_kit/rapid_kit.dart';
import '../../theme.dart';

/// 录像设置页面
class VideosettingPage extends StatefulWidget {
  final String deviceId;

  const VideosettingPage({
    super.key,
    required this.deviceId,
  });

  @override
  State<StatefulWidget> createState() {
    return _VideosettingPageState();
  }
}

class _VideosettingPageState extends State<VideosettingPage> {
  late String _deviceId;

  // 指令示例
  late Pipe _pipe;

  // 录像模式 0 - 不录象
  int _recordType = 0;

  // 录像清晰程度
  int _recordQuality = 0;

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId;

    LogUtils.w("设备ID${_deviceId}");

    // 创建实例
    _pipe = Pipe.create(_deviceId);
    // 连接设备
    _pipe.establish();

    // _pipe.listen((state) {
    //   LogUtils.w(state);
    //   if (state == PipeState.established) {
    //     // 连接成功建立，可以启动视频播放、发送指令或者其他操作了
    //     _onQuality();
    //   }
    // });

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff),
      statusBarIconBrightness: Brightness.dark,
    ));

    WidgetsBinding.instance.addPostFrameCallback((_) {
      print("页面渲染完毕");
      _onQuality();
    });
  }

  @override
  void dispose() {
    super.dispose();
    // 销毁实例
    _pipe.abolish();
    _pipe.destroy();
  }

  void _onQuality() async {
    if (!_pipe.isEstablished) return;
    LogUtils.w("========执行=======");
    final resp = await InstructStandard.recordingProfile(_pipe);
    if (!mounted) return;
    if (resp.success) {
      LogUtils.w(resp.data!.recordType);
      LogUtils.w(resp.data!.recordQuality);
      setState(() {
         _recordType = resp.data!.recordType;
         _recordQuality = resp.data!.recordQuality;
      });
    } else {
      showToast("获取画面设置失败");
    }
  }

  Future<bool> _onWillPop() async {
    // HomePageState.globalKeytwo.currentState?.reloadData();
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        backgroundColor: Color(0xFFF2F3F5),
        appBar: _buildTitleBar(context),
        body: Padding(
          padding: EdgeInsets.fromLTRB(10, 16, 10, 16), // 这里设置内边距，可以根据需要调整数值
          child: Column(
            children: [
              // 添加本地图片
              _buildreportoneRow(),
              SizedBox(height: 20),
              _buildreportRow(),
            ],
          ),
        ),
      ),
      onWillPop: _onWillPop,
    );
  }

  // 录像模式
  Widget _buildreportoneRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 5, // 上边距
        bottom: 5, // 下边距
        left: 5, // 左边距
        right: 5, // 右边距
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.only(
              top: 10, // 上边距
              bottom: 0, // 下边距
              left: 10, // 左边距
              right: 0, // 右边距
            ),
            child: Text(
              '存储卡录像模式',
              style: TextStyle(fontSize: 14, color: Color(0xFF6c6c6c)),
            ),
          ),
          // 第一行：0°
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(8.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '全天录像',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        '不间断的连续录像',
                        style: TextStyle(fontSize: 14, color: Colors.grey),
                      ),
                    ],
                  ),
                  Radio(
                    value: 2,
                    groupValue: _recordType,
                    onChanged: (value) async {
                      try {
                        if (!_pipe.isEstablished) {
                          showToast("管道未建立");
                          return;
                        }

                        LogUtils.w("========执行正常=======");

                        RecordingProfile profile = RecordingProfile(2, _recordQuality);
                        final resp = await InstructStandard.setRecordingProfile(_pipe,profile);
                        if (!mounted) return;

                        if (resp.success) {
                          setState(() {
                            _recordType = 2;
                          });
                          showToast("设置成功");
                        } else {
                          showToast("设置失败");
                        }
                      } catch (e) {
                        LogUtils.e("设置失败: $e");
                        showToast("设置失败，请重试");
                      }
                    },
                    activeColor: SampleThemeConfigure.colorPrimary,
                  ),
                ],
              ),
            ),
          ),
          // 第二行：180°
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(8.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '事件录制',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        '当侦测到事件时进行录像',
                        style: TextStyle(fontSize: 14, color: Colors.grey),
                      ),
                    ],
                  ),
                  Radio(
                    value: 1,
                    groupValue: _recordType,
                    onChanged: (value) async {
                      if (!_pipe.isEstablished) return;
                      LogUtils.w("========执行正常=======");
                      RecordingProfile profile = RecordingProfile(1, _recordQuality);
                      final resp = await InstructStandard.setRecordingProfile(_pipe,profile);
                      if (!mounted) return;
                      if (resp.success) {
                        setState(() {
                          _recordType = 1;
                        });
                        showToast("设置成功");
                      } else {
                        showToast("设置失败");
                      }
                    },
                    activeColor: SampleThemeConfigure.colorPrimary,
                  ),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(8.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '关闭',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        '关闭后设备将停止录像',
                        style: TextStyle(fontSize: 14, color: Colors.grey),
                      ),
                    ],
                  ),
                  Radio(
                    value: 0,
                    groupValue: _recordType,
                    onChanged: (value) async {
                      if (!_pipe.isEstablished) return;
                      LogUtils.w("========执行正常=======");
                      RecordingProfile profile = RecordingProfile(0, _recordQuality);
                      final resp = await InstructStandard.setRecordingProfile(_pipe,profile);
                      if (!mounted) return;
                      if (resp.success) {
                        setState(() {
                          _recordType = 0;
                        });
                        showToast("设置成功");
                      } else {
                        showToast("设置失败");
                      }
                    },
                    activeColor: SampleThemeConfigure.colorPrimary,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 清晰度
  Widget _buildreportRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 5, // 上边距
        bottom: 5, // 下边距
        left: 5, // 左边距
        right: 5, // 右边距
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.only(
              top: 10, // 上边距
              bottom: 0, // 下边距
              left: 10, // 左边距
              right: 0, // 右边距
            ),
            child: Text(
              '存储卡存储清晰程度',
              style: TextStyle(fontSize: 14, color: Color(0xFF6c6c6c)),
            ),
          ),
          // 第一行：0°
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(8.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '标清',
                    style: TextStyle(fontSize: 16),
                  ),
                  Radio(
                    value: 1,
                    groupValue: _recordQuality,
                    onChanged: (value) async {
                      try {
                        if (!_pipe.isEstablished) {
                          showToast("管道未建立");
                          return;
                        }

                        LogUtils.w("========执行正常=======");
                        RecordingProfile profile = RecordingProfile(_recordType, 1);
                        final resp = await InstructStandard.setRecordingProfile(_pipe,profile);

                        if (!mounted) return;

                        if (resp.success) {
                          setState(() {
                            _recordQuality = 1;
                          });
                          showToast("设置成功");
                        } else {
                          showToast("设置失败");
                        }
                      } catch (e) {
                        LogUtils.e("设置失败: $e");
                        showToast("设置失败，请重试");
                      }
                    },
                    activeColor: SampleThemeConfigure.colorPrimary,
                  ),
                ],
              ),
            ),
          ),
          // 第二行：180°
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(8.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '高清',
                    style: TextStyle(fontSize: 16),
                  ),
                  Radio(
                    value: 0,
                    groupValue: _recordQuality,
                    onChanged: (value) async {
                      if (!_pipe.isEstablished) return;
                      LogUtils.w("========执行正常=======");
                      RecordingProfile profile = RecordingProfile(_recordType, 0);
                      final resp = await InstructStandard.setRecordingProfile(_pipe,profile);
                      if (!mounted) return;
                      if (resp.success) {
                        setState(() {
                          _recordQuality = 0;
                        });
                        showToast("设置成功");
                      } else {
                        showToast("设置失败");
                      }
                    },
                    activeColor: SampleThemeConfigure.colorPrimary,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 导航
  AppBar _buildTitleBar(BuildContext context) {
    return AppBar(
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          _onWillPop();
          Navigator.of(context).pop();
        },
      ),
      automaticallyImplyLeading: false,
      title: Text(
        "录像设置",
        style: TextStyle(
          fontSize: 17,
          fontFamily: "PingFang SC",
          fontWeight: FontWeight.w600,
        ),
      ),
      centerTitle: true,
    );
  }
}
